<template>
  <view class="smart-travel">
    <!-- 页面头部 -->
    <view class="header">
      <view class="nav-bar">
        <view class="back-btn" @click="goBack">
          <text class="iconfont icon-arrow-left">←</text>
        </view>
        <text class="page-title">旅游路线规划</text>
        <view class="action-btn" @click="toggleManualInput">
          <text class="iconfont" :class="showManualInput ? 'icon-close' : 'icon-plus'">{{ showManualInput ? '×' : '+'
            }}</text>
        </view>
      </view>

      <!-- 旅行信息卡片 -->
      <view class="travel-info-card">
        <text class="travel-title">{{ travelTitle }}</text>
        <text class="travel-subtitle" v-if="attractions.length">{{ attractions.length }}个景点 · {{ getTotalDistance()
          }}公里</text>
      </view>
    </view>

    <!-- 手动添加景点表单 -->
    <view class="input-form" v-if="showManualInput">
      <view class="form-row">
        <view class="form-item">
          <text class="form-label">城市</text>
          <input class="form-input" v-model="manualCity" placeholder="请选择城市名称" @click="gotofindcity" disabled />
        </view>
      </view>
      <view class="form-row">
        <view class="form-item">
          <text class="form-label">景点</text>
          <view class="form-input-container">
            <input class="form-input" v-model="manualAttractionName" placeholder="请输入景点名称，如：故宫博物院" disabled />
            <button class="add-btn" @click="addManualAttraction">
              <text class="btn-text">添加</text>
            </button>
          </view>
        </view>
      </view>
    </view>

    <!-- 出行方式选择 -->
    <view class="travel-mode-selector" v-if="attractions.length >= 2">
      <view class="travel-mode-tabs">
        <view v-for="(mode, index) in travelModes" :key="index"
          :class="['mode-tab', currentMode === mode.key ? 'active' : '']" @click="changeMode(mode.key)">
          <text class="iconfont" :class="mode.icon">{{ getModeIcon(mode.key) }}</text>
          <text class="mode-name">{{ mode.name }}</text>
        </view>
      </view>
    </view>

    <!-- 地图容器 -->
    <view class="map-container">
      <!-- 交互式地图 -->
      <map v-if="attractions.length > 0 && !loading" class="interactive-map" :latitude="mapCenter.latitude"
        :longitude="mapCenter.longitude" :markers="mapMarkers" :polyline="mapPolyline" :scale="mapScale"
        :show-location="true" :enable-zoom="true" :enable-scroll="true" :enable-rotate="true" @markertap="onMarkerTap"
        @callouttap="onCalloutTap">
        <!-- 自定义地图控件 -->
        <cover-view class="map-controls">
          <cover-view class="map-control zoom-in" @click="zoomMap(true)">+</cover-view>
          <cover-view class="map-control zoom-out" @click="zoomMap(false)">-</cover-view>
          <cover-view class="map-control location" @click="moveToCurrentLocation">📍</cover-view>
        </cover-view>

        <!-- 景点信息卡片 -->
        <cover-view class="map-info-card" v-if="selectedMarker !== null">
          <cover-view class="info-card-content">
            <cover-view class="info-card-title">{{ getSelectedAttractionName() }}</cover-view>
            <cover-view class="info-card-address" v-if="getSelectedAttractionAddress()">{{
              getSelectedAttractionAddress() }}</cover-view>
            <cover-view class="info-card-actions">
              <cover-view class="card-action navigate" @click="navigateToAttraction">导航</cover-view>
              <cover-view class="card-action close" @click="closeInfoCard">关闭</cover-view>
            </cover-view>
          </cover-view>
        </cover-view>
      </map>

      <!-- 加载状态 -->
      <view v-if="loading" class="loading-state">
        <view class="loading-content">
          <text class="iconfont icon-loading">🔄</text>
          <text class="loading-text">正在规划路线...</text>
        </view>
      </view>

      <!-- 错误状态 -->
      <view v-if="error" class="error-state">
        <view class="error-content">
          <text class="iconfont icon-warning">⚠️</text>
          <text class="error-text">{{ error }}</text>
          <view class="retry-btn" @click="generateMap">重试</view>
        </view>
      </view>

      <!-- 无内容状态 -->
      <view v-if="!attractions.length && !loading && !error" class="empty-state">
        <text class="iconfont icon-location">📍</text>
        <text class="empty-text">添加至少两个景点来规划路线</text>
      </view>
    </view>

    <!-- 路线详情 -->
    <view class="route-details" v-if="attractions.length >= 2 && routeSummary">
      <view class="route-summary">
        <view class="summary-item">
          <text class="summary-value">{{ formatDistance(routeSummary.distance) }}</text>
          <text class="summary-label">总距离</text>
        </view>
        <view class="summary-item">
          <text class="summary-value">{{ formatDuration(routeSummary.duration) }}</text>
          <text class="summary-label">预计用时</text>
        </view>
        <view class="summary-item" v-if="routeSummary.cost">
          <text class="summary-value">¥{{ routeSummary.cost }}</text>
          <text class="summary-label">预计花费</text>
        </view>
      </view>

      <view class="route-segments" v-if="attractionDistances.length">
        <view class="segment-header">
          <text class="segment-title">景点间距离</text>
        </view>

        <view class="segments-container">
          <view class="segment-item" v-for="(segment, index) in attractionDistances" :key="index">
            <view class="segment-marker">
              <text class="segment-index">{{ index + 1 }}</text>
            </view>
            <view class="segment-content">
              <view class="segment-header">
                <text class="segment-name">{{ segment.from }} → {{ segment.to }}</text>
                <text class="segment-distance">{{ segment.distance }} 公里</text>
              </view>
              <text class="segment-detail">预计用时: {{ segment.duration }} 分钟</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 景点列表 -->
    <view class="attractions-panel">
      <view class="panel-header">
        <text class="panel-title">景点列表</text>
        <text class="panel-count">{{ attractions.length }}</text>
      </view>

      <view v-if="hasDayInfo" class="day-attractions-container">
        <view class="section-title">景点行程安排</view>

        <view v-for="(attractions, dayTitle) in groupedAttractions" :key="dayTitle" class="day-group">
          <view class="day-title">{{ dayTitle }}</view>
          <view class="day-attractions-list">
            <view v-for="(item, index) in attractions" :key="index" class="attraction-item"
              @click="selectAttraction(item)">
              <view class="attraction-name">{{ item.name }}</view>
              <view v-if="item.dayDesc" class="attraction-desc">{{ item.dayDesc }}</view>
            </view>
          </view>
        </view>
      </view>

      <view v-if="!hasDayInfo" class="attractions-list" scroll-y>
        <view class="attraction-item" v-for="(item, index) in attractions" :key="index" :class="{
          'dragging': dragState.isDragging && dragState.startIndex === index,
          'drag-target': dragState.isDragging && dragState.currentIndex === index
        }" :style="dragState.startIndex === index ? dragState.dragItemStyle : ''"
          @touchstart="(e) => dragStart(e, index)" @touchmove="dragMove" @touchend="dragEnd">
          <view class="drag-handle">
            <text class="iconfont icon-drag">⋮</text>
          </view>
          <view class="attraction-marker" :class="getMarkerClass(index)">
            <text class="marker-text">{{ String.fromCharCode(65 + index) }}</text>
          </view>
          <view class="attraction-info">
            <text class="attraction-name">{{ item.originalName || item.name }}</text>
            <text class="attraction-schedule" v-if="item.dayTitle">{{ item.dayTitle }} · {{ item.timeSlot }}</text>
          </view>
          <view class="attraction-action" @click="removeAttraction(index)">
            <text class="iconfont icon-delete">×</text>
          </view>
        </view>

        <view class="empty-list" v-if="!attractions.length">
          <text class="empty-icon">🏞️</text>
          <text class="empty-text">暂无景点，请添加景点</text>
        </view>
      </view>

      <view class="panel-footer" v-if="attractions.length >= 2">
        <button class="action-button primary" @click="regenerateRoute">
          <text class="iconfont icon-refresh">🔄</text>
          <text>重新规划路线</text>
        </button>
        <button class="action-button secondary" @click="saveRouteData">
          <text class="iconfont icon-save">💾</text>
          <text>{{ isExistingRoute ? '修改路线数据' : '保存路线数据' }}</text>
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue';
import {
  getGeocode,
  getStaticMap,
  getDistance,
  getWalkingRoute,
  getDrivingRoute,
  getBusRoute,
  getBikeRoute,
  getIpLocation
} from '@/api/GaoDeApi';
import {
  createRouteData,
  updateRouteData
} from '@/api/travelrouterdata';

// 出行方式常量
const TRAVEL_MODES = {
  WALKING: 'walking',
  DRIVING: 'driving',
  TRANSIT: 'transit',
  BICYCLING: 'bicycling'
};

// 基础数据
const travelTitle = ref('');
const dateRange = ref('');
const city = ref('');
const attractions = ref([]);
const mapUrl = ref('');
const loading = ref(true);
const error = ref('');
const distances = ref([]);
const travelData = ref(null); // 旅行数据对象

// 地图数据
const mapCenter = ref({
  latitude: 39.908823,
  longitude: 116.397470
});
const mapMarkers = ref([]);
const mapPolyline = ref([]);

// 手动输入相关
const showManualInput = ref(false);
const manualCity = ref('');
const manualAttractionName = ref('');

// 路线规划相关
const currentMode = ref(TRAVEL_MODES.WALKING); // 默认步行模式
const routeSummary = ref(null);
const routeSteps = ref([]);
const routeDetails = ref(null);

// 出行方式选项
const travelModes = [
  { key: TRAVEL_MODES.WALKING, name: '步行', icon: 'icon-walk' },
  { key: TRAVEL_MODES.DRIVING, name: '驾车', icon: 'icon-car' },
  { key: TRAVEL_MODES.TRANSIT, name: '公交', icon: 'icon-bus' },
  { key: TRAVEL_MODES.BICYCLING, name: '骑行', icon: 'icon-bike' }
];

// 拖拽状态
const dragState = ref({
  isDragging: false,
  startY: 0,
  currentY: 0,
  startIndex: -1,
  currentIndex: -1,
  itemHeight: 80,
  listTop: 0,
  dragItemStyle: {
    transform: 'translateY(0px)',
    opacity: 1
  }
});

// 地理编码缓存
const geocodeCache = ref({});
const CACHE_EXPIRY = 3 * 60 * 60 * 1000; // 3小时的毫秒数

// 添加新的状态变量
const mapScale = ref(14); // 地图缩放级别
const selectedMarker = ref(null); // 当前选中的标记
const stepsExpanded = ref(false); // 路线步骤是否展开

// 添加按天分组后的景点数据
const groupedAttractions = ref({});
const hasDayInfo = ref(false);

// 格式化工具函数
const formatDistance = (meters) => {
  if (meters >= 1000) {
    return (meters / 1000).toFixed(1) + ' 公里';
  }
  return Math.round(meters) + ' 米';
};
const gotofindcity = () => {
  openCitySelector();
};
const formatDuration = (seconds) => {
  if (!seconds) return '未知';

  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);

  if (hours > 0) {
    return `${hours}小时${minutes > 0 ? minutes + '分钟' : ''}`;
  }
  return `${minutes}分钟`;
};

// 计算总距离
const getTotalDistance = () => {
  if (!routeSummary.value || !routeSummary.value.distance) {
    return '计算中...';
  }
  return (routeSummary.value.distance / 1000).toFixed(1);
};

// 添加地图交互所需的变量
const toggleManualInput = () => {
  showManualInput.value = !showManualInput.value;
  if (showManualInput.value && !city.value) {
    city.value = '北京市';
    manualCity.value = city.value;
  }
};

// 手动添加景点
const addManualAttraction = async () => {
  if (!manualCity.value) {
    uni.showToast({
      title: '请输入城市名称',
      icon: 'none',
      duration: 2000
    });
    return;
  }

  if (!manualAttractionName.value) {
    uni.showToast({
      title: '请输入景点名称',
      icon: 'none',
      duration: 2000
    });
    return;
  }

  // 更新城市
  city.value = manualCity.value;

  loading.value = true;
  error.value = '';

  try {
    // 先尝试对景点进行地理编码
    const address = `${city.value}${manualAttractionName.value}`;
    const response = await getGeocode({
      address: address,
      city: city.value
    });

    if (response.data && response.data.status === '1' && response.data.geocodes && response.data.geocodes.length > 0) {
      const geocode = response.data.geocodes[0];

      // 添加景点
      attractions.value.push({
        name: manualAttractionName.value,
        dayTitle: '自定义行程',
        timeSlot: '全天',
        description: '手动添加的景点',
        location: geocode.location,
        geocode: geocode
      });

      // 清空输入框
      manualAttractionName.value = '';

      // 如果是第一个景点，设置标题
      if (attractions.value.length === 1 && !travelTitle.value) {
        travelTitle.value = `${city.value}旅游路线图`;
      }

      // 如果有两个及以上景点，规划路线
      if (attractions.value.length >= 2) {
        planRoute();
      } else {
        // 否则只生成地图
        prepareInteractiveMapData();
        loading.value = false;
      }

      // 成功提示
      uni.showToast({
        title: '已添加景点',
        icon: 'success',
        duration: 2000
      });
    } else {
      throw new Error('找不到该景点，请检查名称是否正确');
    }
  } catch (err) {
    console.error('添加景点失败:', err);
    error.value = err.message || '添加景点失败，请检查名称是否正确';
    loading.value = false;

    uni.showToast({
      title: error.value,
      icon: 'none',
      duration: 2000
    });
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 处理景点名称格式
const processAttractionName = (name) => {
  // 分割城市和景点名称
  const parts = name.split('+');
  if (parts.length === 2) {
    return {
      city: parts[0],
      name: parts[1],
      fullName: name
    };
  }
  return {
    city: '',
    name: name,
    fullName: name
  };
};

// 获取景点的地理编码（经纬度）
const getAttractionsGeocode = async () => {
  try {
    // 首先复制一份原始景点数据
    const originalAttractions = [...attractions.value];
    const successfulAttractions = [];
    const failedNames = [];

    // 对每个景点进行地理编码查询
    for (let i = 0; i < originalAttractions.length; i++) {
      const attraction = originalAttractions[i];

      // 如果景点已有地理编码，直接使用
      if (attraction.location) {
        successfulAttractions.push(attraction);
        continue;
      }

      // 处理景点名称格式
      const processedName = processAttractionName(attraction.name);

      try {
        // 构建缓存key
        const cacheKey = `${processedName.city}_${processedName.name}`;

        // 检查缓存中是否有有效的地理编码数据
        const cachedGeocode = geocodeCache.value[cacheKey];
        let geocodeData = null;

        if (cachedGeocode && (Date.now() - cachedGeocode.timestamp) < CACHE_EXPIRY) {
          // 使用缓存的地理编码数据
          geocodeData = cachedGeocode.data;
          console.log(`使用缓存的地理编码数据: ${processedName.name}`);
        } else {
          // 构建地址字符串
          const address = processedName.fullName;

          const response = await getGeocode({
            address: address,
            city: processedName.city
          });

          if (response.data && response.data.status === '1' && response.data.geocodes && response.data.geocodes.length > 0) {
            geocodeData = response.data.geocodes[0];

            // 保存到缓存
            geocodeCache.value[cacheKey] = {
              data: geocodeData,
              timestamp: Date.now()
            };
          }
        }

        if (geocodeData) {
          const location = geocodeData.location; // 格式: "经度,纬度"

          // 将成功查询的景点添加到成功列表
          successfulAttractions.push({
            ...attraction,
            name: processedName.name, // 使用清理后的名称
            originalName: attraction.name, // 保留原始名称用于显示
            location: location,
            geocode: geocodeData
          });
        } else {
          console.error(`无法获取景点"${processedName.name}"的地理编码`);
          failedNames.push(attraction.name);
        }
      } catch (queryErr) {
        console.error(`查询景点"${processedName.name}"时出错:`, queryErr);
        failedNames.push(attraction.name);
      }

      // 每次API调用后添加小延迟，避免请求过于频繁
      await new Promise(resolve => setTimeout(resolve, 100));
    }

    // 更新景点列表为成功获取地理编码的景点
    if (successfulAttractions.length > 0) {
      attractions.value = successfulAttractions;
      if (failedNames.length > 0) {
        console.warn(`以下景点未能获取地理编码：${failedNames.join(', ')}`);
      }

      // 保存地理编码缓存到本地存储
      saveGeocodeCache();
      return true;
    } else {
      error.value = '无法获取任何景点的位置信息，请尝试手动输入';
      return false;
    }
  } catch (err) {
    console.error('获取地理编码失败:', err);
    error.value = '获取景点位置信息失败';
    return false;
  }
};

// 保存地理编码缓存到本地存储
const saveGeocodeCache = () => {
  try {
    uni.setStorageSync('geocodeCache', JSON.stringify({
      data: geocodeCache.value,
      timestamp: Date.now()
    }));
  } catch (e) {
    console.error('保存地理编码缓存失败:', e);
  }
};

// 从本地存储加载地理编码缓存
const loadGeocodeCache = () => {
  try {
    const cached = uni.getStorageSync('geocodeCache');
    if (cached) {
      const parsedCache = JSON.parse(cached);
      if (Date.now() - parsedCache.timestamp < CACHE_EXPIRY) {
        geocodeCache.value = parsedCache.data;
        console.log('已加载地理编码缓存');
      } else {
        uni.removeStorageSync('geocodeCache');
        console.log('地理编码缓存已过期，已清除');
      }
    }
  } catch (e) {
    console.error('加载地理编码缓存失败:', e);
  }
};

// 计算景点之间的距离
const calculateDistances = async () => {
  try {
    const distanceItems = [];

    // 只计算相邻景点之间的距离
    for (let i = 0; i < attractions.value.length - 1; i++) {
      const origin = attractions.value[i];
      const destination = attractions.value[i + 1];

      if (origin.location && destination.location) {
        const response = await getDistance({
          origins: origin.location,
          destination: destination.location,
          type: '1' // 驾车距离
        });

        if (response.data && response.data.status === '1' && response.data.results && response.data.results.length > 0) {
          const result = response.data.results[0];
          const distanceInKm = (result.distance / 1000).toFixed(1);

          distanceItems.push({
            from: origin.name,
            to: destination.name,
            distance: distanceInKm,
            duration: Math.ceil(result.duration / 60) // 转换为分钟
          });
        }
      }
    }

    distances.value = distanceItems;
    return true;
  } catch (err) {
    console.error('计算距离失败:', err);
    return false;
  }
};

// 生成静态地图URL
const generateStaticMapUrl = () => {
  if (attractions.value.length === 0 || !attractions.value[0].location) {
    return null;
  }

  try {
    // 构建标记点参数
    const markers = attractions.value.map((attraction, index) => {
      const label = String.fromCharCode(65 + index); // A, B, C...
      return `mid,0x0000FF,${label}:${attraction.location}`;
    }).join('|');

    // 构建路径参数（连接各个景点）
    const locations = attractions.value.map(attraction => attraction.location).join(';');
    const paths = `10,0x0000ff,1,,:${locations}`;

    // 确定地图中心点（使用第一个景点位置）
    const center = attractions.value[0].location;

    // 构建静态地图URL
    const params = {
      location: center,
      zoom: 13,
      size: '750*500',
      markers: markers,
      paths: paths
    };

    // 生成静态地图URL(改为直接返回拼接的URL，因为小程序可能无法处理重定向)
    const baseUrl = 'https://restapi.amap.com/v3/staticmap';
    const key = '801794fb48c62230cdc3026bdb96f75b'; // 使用现有key

    let url = `${baseUrl}?location=${params.location}&zoom=${params.zoom}&size=${params.size}&key=${key}`;

    if (markers) {
      url += `&markers=${encodeURIComponent(markers)}`;
    }

    if (paths) {
      url += `&paths=${encodeURIComponent(paths)}`;
    }

    return url;
  } catch (err) {
    console.error('生成地图URL失败:', err);
    return null;
  }
};

// 生成地图
const generateMap = async () => {
  loading.value = true;
  error.value = '';
  mapUrl.value = '';

  try {
    // 获取各景点的地理编码
    const geocodeSuccess = await getAttractionsGeocode();
    if (!geocodeSuccess) {
      error.value = '无法获取景点位置信息';
      loading.value = false;
      return;
    }

    // 规划路线
    if (attractions.value.length >= 2) {
      await planRoute();
    } else {
      // 如果只有一个景点，只显示地图标记
      prepareInteractiveMapData();
    }
  } catch (err) {
    console.error('生成地图失败:', err);
    error.value = '生成地图时出错';
  } finally {
    loading.value = false;
  }
};

// 准备交互式地图数据
const prepareInteractiveMapData = () => {
  if (attractions.value.length === 0) {
    return;
  }

  try {
    // 准备地图中心点（使用第一个景点的位置）
    const firstLocation = attractions.value[0].location;
    if (firstLocation) {
      const [longitude, latitude] = firstLocation.split(',').map(Number);
      mapCenter.value = { latitude, longitude };
    }

    // 准备标记点
    const markers = attractions.value.map((attraction, index) => {
      const [longitude, latitude] = attraction.location.split(',').map(Number);
      return {
        id: index,
        latitude,
        longitude,
        title: attraction.originalName || attraction.name,
        callout: {
          content: String.fromCharCode(65 + index),
          color: '#FFFFFF',
          fontSize: 14,
          textAlign: 'center',
          bgColor: '#007AFF',
          borderRadius: 15,
          padding: 5,
          display: 'ALWAYS'
        }
      };
    });
    mapMarkers.value = markers;

    // 准备路线
    const points = attractions.value.map(attraction => {
      const [longitude, latitude] = attraction.location.split(',').map(Number);
      return { latitude, longitude };
    });

    if (points.length > 0) {
      // 根据出行方式设置不同颜色
      let pathColor = '#007AFF'; // 默认蓝色

      switch (currentMode.value) {
        case TRAVEL_MODES.WALKING:
          pathColor = '#4CD964'; // 绿色
          break;
        case TRAVEL_MODES.DRIVING:
          pathColor = '#007AFF'; // 蓝色
          break;
        case TRAVEL_MODES.TRANSIT:
          pathColor = '#5856D6'; // 紫色
          break;
        case TRAVEL_MODES.BICYCLING:
          pathColor = '#FF9500'; // 橙色
          break;
      }

      mapPolyline.value = [{
        points,
        color: pathColor,
        width: 4,
        arrowLine: true
      }];
    }
  } catch (err) {
    console.error('准备交互式地图数据失败:', err);
  }
};



// 按天分组景点
const groupAttractionsByDay = () => {
  const grouped = {};

  // 遍历所有景点并按天分组
  attractions.value.forEach(attraction => {
    const dayTitle = attraction.dayTitle || '未分类';
    if (!grouped[dayTitle]) {
      grouped[dayTitle] = [];
    }
    grouped[dayTitle].push(attraction);
  });

  // 更新分组数据
  groupedAttractions.value = grouped;
  console.log('按天分组后的景点:', groupedAttractions.value);
};

// 从travelData中获取景点数据
const getAttractions = () => {
  if (!travelData.value || !travelData.value.attractions) {
    return [];
  }

  return travelData.value.attractions.map(item => {
    // 确保返回一个标准化的景点对象，保留所有原始属性
    return {
      name: item.name,
      description: item.description || '景点',
      location: item.location || null,
      dayTitle: item.dayTitle || null,
      dayDesc: item.dayDesc || null,
      originalName: item.originalName || item.name,
      ...(item.geocode ? { geocode: item.geocode } : {})
    };
  });
};

// 初始化
onMounted(() => {
  // 从本地存储获取旅行数据
  try {
    const travelDataStr = uni.getStorageSync('travelRouteData');
    if (travelDataStr) {
      travelData.value = JSON.parse(travelDataStr);
      console.log('加载旅行数据成功:', travelData.value);

      // 设置基本信息
      travelTitle.value = travelData.value.title || '旅游路线图';
      dateRange.value = travelData.value.dateRange || '';
      city.value = travelData.value.city || '';
      manualCity.value = travelData.value.city || '杭州';

      // 设置路线数据相关状态
      if (travelData.value.id) {
        routeDataId.value = travelData.value.id;
      }

      isExistingRoute.value = travelData.value.isExistingRoute || false;
      travelPlanId.value = travelData.value.travelPlanId || null;

      // 检查景点是否包含天数信息
      hasDayInfo.value = checkDayInfo(travelData.value.attractions);
      console.log('是否包含天数信息:', hasDayInfo.value);

      // 如果包含天数信息，按天分组景点
      if (hasDayInfo.value) {
        // 获取所有景点
        attractions.value = travelData.value.attractions || [];
        // 按天分组景点
        groupAttractionsByDay();
      } else {
        // 常规处理
        attractions.value = getAttractions();
      }

      // 生成地图
      if (attractions.value.length > 0) {
        generateMap();
      }
    } else {

      // 初始化默认数据
      travelTitle.value = '自定义旅游路线图';
      city.value = '';
      manualCity.value = '杭州';
      attractions.value = [];
      loading.value = false;
      error.value = '请添加您想要游览的景点';
      showManualInput.value = true;
    }
  } catch (e) {
    console.error('解析旅行数据失败:', e);
    // 初始化默认数据
    travelTitle.value = '自定义旅游路线图';
    city.value = '';
    manualCity.value = '杭州';
    attractions.value = [];
    loading.value = false;
    error.value = '请添加您想要游览的景点';
    showManualInput.value = true;
  }

  // 获取城市地理位置
  if (manualCity.value) {
    moveToCurrentLocation();
  }

  // 监听城市选择事件
  uni.$on('city-selected-AI-travel', (selectedCity) => {
    console.log('接收到城市选择事件:', selectedCity);
    if (selectedCity) {
      manualCity.value = selectedCity.city;
      city.value = selectedCity.city;

      // 清空之前的景点
      attractions.value = [];
      mapMarkers.value = [];

      // 移动地图到所选城市
      moveToCity(selectedCity.city);
    }
  });
});

// 组件销毁时移除事件监听
onUnmounted(() => {
  uni.$off('city-selected-AI-travel');
});

// 移动地图到指定城市
const moveToCity = async (cityName) => {
  try {
    // 获取城市地理编码
    const response = await getGeocode({
      address: cityName
    });

    if (response.data && response.data.status === '1' && response.data.geocodes && response.data.geocodes.length > 0) {
      const location = response.data.geocodes[0].location; // 格式: "经度,纬度"
      const [longitude, latitude] = location.split(',').map(Number);

      mapCenter.value = {
        latitude,
        longitude
      };
    } else {
      console.error('获取城市地理编码失败:', response);
    }
  } catch (err) {
    console.error('移动地图到城市失败:', err);
  }
};

// 移除某个景点
const removeAttraction = (index) => {
  attractions.value.splice(index, 1);

  // 重新规划路线
  if (attractions.value.length >= 2) {
    planRoute();
  } else {
    // 如果只剩一个或没有景点，重置路线信息
    routeSummary.value = null;
    routeSteps.value = [];
    prepareInteractiveMapData();
  }
};

// 页面卸载时保存缓存
onUnmounted(() => {
  // 保存地理编码缓存
  saveGeocodeCache();

  // 清理临时存储的路线数据
  try {
    uni.removeStorageSync('travelRouteData');
    console.log('已清理临时存储的路线数据');
  } catch (err) {
    console.error('清理数据失败:', err);
  }
});

// 重新检查存储的数据
const checkStoredData = () => {
  loading.value = true;
  error.value = '';

  try {
    // 重新检查存储中是否有数据
    const storedData = uni.getStorageSync('travelRouteData');

    if (storedData) {
      const data = JSON.parse(storedData);
      console.log('重新加载存储的路线数据:', data);

      // 使用读取到的数据
      travelTitle.value = data.title || '旅游路线图';
      dateRange.value = data.dateRange || '';
      city.value = data.city || '';
      manualCity.value = data.city || '杭州市';
      attractions.value = data.attractions || [];

      // 检查景点是否包含天数信息，用于决定展示方式
      const hasDayInfo = checkDayInfo(data.attractions);

      // 如果包含天数信息，按天分组景点
      if (hasDayInfo) {
        groupAttractionsByDay();
      }

      // 生成地图
      if (attractions.value.length > 0) {
        generateMap();
        return;
      } else {
        error.value = '未找到景点信息，请手动添加';
        showManualInput.value = true;
      }
    } else {
      error.value = '未找到存储的数据，请手动添加景点';
      showManualInput.value = true;
    }
  } catch (err) {
    console.error('检查存储数据失败:', err);
    error.value = '加载数据失败，请手动添加景点';
    showManualInput.value = true;
  } finally {
    loading.value = false;
  }
};

// 拖拽功能
const dragStart = (e, index) => {
  const touch = e.touches[0];
  const query = uni.createSelectorQuery();

  query.select('.attractions-list').boundingClientRect(rect => {
    if (rect) {
      dragState.value = {
        ...dragState.value,
        isDragging: true,
        startY: touch.clientY,
        currentY: touch.clientY,
        startIndex: index,
        currentIndex: index,
        listTop: rect.top,
        dragItemStyle: {
          transform: 'translateY(0px)',
          opacity: 0.8
        }
      };
    }
  }).exec();
};

const dragMove = (e) => {
  if (!dragState.value.isDragging) return;

  const touch = e.touches[0];
  const moveY = touch.clientY - dragState.value.startY;
  const newIndex = Math.round((moveY + dragState.value.itemHeight / 2) / dragState.value.itemHeight);

  // 计算新的索引位置
  let targetIndex = dragState.value.startIndex + newIndex;
  targetIndex = Math.max(0, Math.min(targetIndex, attractions.value.length - 1));

  // 更新拖拽项的位置
  dragState.value = {
    ...dragState.value,
    currentY: touch.clientY,
    currentIndex: targetIndex,
    dragItemStyle: {
      transform: `translateY(${moveY}px)`,
      opacity: 0.8
    }
  };
};

const dragEnd = () => {
  if (!dragState.value.isDragging) return;

  const { startIndex, currentIndex } = dragState.value;

  // 如果位置发生变化，更新景点列表顺序
  if (startIndex !== currentIndex && startIndex !== -1 && currentIndex !== -1) {
    const newAttractions = [...attractions.value];
    const [draggedItem] = newAttractions.splice(startIndex, 1);
    newAttractions.splice(currentIndex, 0, draggedItem);
    attractions.value = newAttractions;

    // 重新规划路线
    if (attractions.value.length >= 2) {
      planRoute();
    } else {
      prepareInteractiveMapData();
    }
  }

  // 重置拖拽状态
  dragState.value = {
    ...dragState.value,
    isDragging: false,
    startIndex: -1,
    currentIndex: -1,
    dragItemStyle: {
      transform: 'translateY(0px)',
      opacity: 1
    }
  };
};

// 重新规划路线
const regenerateRoute = () => {
  planRoute();
};

// 保存路线数据
const saveRouteData = async () => {
  if (attractions.value.length < 2) {
    uni.showToast({
      title: '至少需要两个景点才能保存',
      icon: 'none'
    });
    return;
  }

  uni.showLoading({
    title: isExistingRoute.value ? '更新路线中...' : '保存路线中...',
    mask: true
  });

  try {
    // 构建路线数据对象
    const routeData = {
      city: city.value,
      title: travelTitle.value,
      dateRange: dateRange.value,
      attractions: attractions.value,
      travelPlanId: travelPlanId.value
    };

    let response;

    if (isExistingRoute.value && routeDataId.value) {
      // 更新已有路线数据
      response = await updateRouteData(routeDataId.value, routeData);
    } else {
      // 创建新的路线数据
      response = await createRouteData(routeData);
    }

    uni.hideLoading();

    if (response.code === 200 || response.code === 201) {
      // 保存成功后更新本地状态
      if (!isExistingRoute.value) {
        isExistingRoute.value = true;
        routeDataId.value = response.data.id;
      }

      uni.showToast({
        title: isExistingRoute.value ? '路线更新成功' : '路线保存成功',
        icon: 'success'
      });

      // 更新本地存储的数据
      updateLocalStorage();
    } else {
      uni.showToast({
        title: '保存失败：' + (response.msg || '未知错误'),
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error('保存路线数据失败:', error);
    uni.showToast({
      title: '保存失败，请稍后重试',
      icon: 'none'
    });
  }
};

// 更新本地存储的路线数据
const updateLocalStorage = () => {
  try {
    const localData = {
      id: routeDataId.value,
      city: city.value,
      title: travelTitle.value,
      dateRange: dateRange.value,
      attractions: attractions.value,
      timestamp: new Date().getTime(),
      travelPlanId: travelPlanId.value,
      isExistingRoute: true
    };

    uni.setStorageSync('travelRouteData', JSON.stringify(localData));
  } catch (e) {
    console.error('更新本地存储失败:', e);
  }
};

// 改变出行方式
const changeMode = (mode) => {
  if (currentMode.value === mode) return;

  currentMode.value = mode;
  loading.value = true;
  error.value = '';

  // 重新规划路线
  planRoute();
};

// 根据选择的出行方式和景点规划路线
const planRoute = async () => {
  if (attractions.value.length < 2) {
    error.value = '至少需要两个景点才能规划路线';
    loading.value = false;
    return;
  }

  loading.value = true;
  error.value = '';

  try {
    // 确保所有景点都有地理编码
    const hasGeocode = await getAttractionsGeocode();
    if (!hasGeocode) {
      error.value = '无法获取部分景点的位置信息';
      loading.value = false;
      return;
    }

    // 处理第一段路线（起点到第一个景点）
    let totalDistance = 0;
    let totalDuration = 0;
    let totalCost = 0;
    let distanceSegments = [];

    // 逐段规划路线（从第一个景点到最后一个景点）
    for (let i = 0; i < attractions.value.length - 1; i++) {
      const origin = attractions.value[i];
      const destination = attractions.value[i + 1];

      if (!origin.location || !destination.location) {
        continue;
      }

      const segmentResult = await planSegmentRoute(origin.location, destination.location);

      if (segmentResult.success) {
        // 累加距离、时间和费用
        totalDistance += segmentResult.distance;
        totalDuration += segmentResult.duration;
        if (segmentResult.cost) totalCost += segmentResult.cost;

        // 添加距离段信息
        distanceSegments.push({
          from: origin.originalName || origin.name,
          to: destination.originalName || destination.name,
          distance: (segmentResult.distance / 1000).toFixed(1),
          duration: Math.ceil(segmentResult.duration / 60)
        });
      } else {
        console.error(`规划路段 ${origin.name} 到 ${destination.name} 失败:`, segmentResult.error);
      }
    }

    // 更新路线摘要信息
    routeSummary.value = {
      distance: totalDistance,
      duration: totalDuration,
      cost: currentMode.value === TRAVEL_MODES.TRANSIT ? totalCost : null
    };

    // 更新景点间距离信息
    attractionDistances.value = distanceSegments;

    // 准备地图显示数据
    prepareInteractiveMapData();

  } catch (err) {
    console.error('规划路线失败:', err);
    error.value = '路线规划失败，请稍后重试';
  } finally {
    loading.value = false;
  }
};

// 规划单段路线
const planSegmentRoute = async (originLocation, destinationLocation) => {
  try {
    let apiResponse;
    const [originLng, originLat] = originLocation.split(',');
    const [destLng, destLat] = destinationLocation.split(',');

    const params = {
      origin: originLocation,
      destination: destinationLocation
    };

    // 根据出行方式调用不同的API
    switch (currentMode.value) {
      case TRAVEL_MODES.WALKING:
        apiResponse = await getWalkingRoute(params);
        break;
      case TRAVEL_MODES.DRIVING:
        apiResponse = await getDrivingRoute({
          ...params,
          strategy: '10' // 默认策略：躲避拥堵 + 最短路径
        });
        break;
      case TRAVEL_MODES.TRANSIT:
        apiResponse = await getBusRoute({
          ...params,
          city: city.value,
          strategy: '0' // 最快捷模式
        });
        break;
      case TRAVEL_MODES.BICYCLING:
        apiResponse = await getBikeRoute(params);
        break;
      default:
        apiResponse = await getWalkingRoute(params);
    }

    // 处理API响应
    if (apiResponse.data && apiResponse.data.status === '1') {
      const responseData = apiResponse.data;

      // 处理不同交通方式的响应格式
      if (currentMode.value === TRAVEL_MODES.WALKING) {
        const route = responseData.route;
        const path = route.paths[0];

        return {
          success: true,
          distance: Number(path.distance),
          duration: Number(path.duration),
          steps: []
        };
      }
      else if (currentMode.value === TRAVEL_MODES.DRIVING) {
        const route = responseData.route;
        const path = route.paths[0];

        return {
          success: true,
          distance: Number(path.distance),
          duration: Number(path.duration),
          steps: []
        };
      }
      else if (currentMode.value === TRAVEL_MODES.TRANSIT) {
        const route = responseData.route;
        const transits = route.transits[0];

        // 提取公交路线信息
        let cost = 0;

        transits.segments.forEach(segment => {
          // 处理公交/地铁段
          if (segment.bus && segment.bus.buslines && segment.bus.buslines.length) {
            const busline = segment.bus.buslines[0];
            cost += Number(busline.fare || 0);
          }
        });

        return {
          success: true,
          distance: Number(transits.distance),
          duration: Number(transits.duration),
          cost: cost,
          steps: []
        };
      }
      else if (currentMode.value === TRAVEL_MODES.BICYCLING) {
        console.log(responseData, 'responseData');

        const route = responseData.route;
        const path = route.paths[0];
        return {
          success: true,
          distance: Number(path.distance),
          duration: Number(path.duration),
          steps: []
        };
      }
    }

    return {
      success: false,
      error: '无法规划路线'
    };
  } catch (err) {
    console.error('规划路段失败:', err);
    return {
      success: false,
      error: err.message || '规划路线出错'
    };
  }
};

// 获取出行方式图标
const getModeIcon = (mode) => {
  switch (mode) {
    case TRAVEL_MODES.WALKING:
      return '🚶';
    case TRAVEL_MODES.DRIVING:
      return '🚗';
    case TRAVEL_MODES.TRANSIT:
      return '🚌';
    case TRAVEL_MODES.BICYCLING:
      return '🚲';
    default:
      return '🚶';
  }
};

// 获取标记样式类
const getMarkerClass = (index) => {
  if (selectedMarker.value === index) {
    return 'attraction-marker selected';
  }

  // 根据出行方式设置不同颜色
  switch (currentMode.value) {
    case TRAVEL_MODES.WALKING:
      return 'attraction-marker walking';
    case TRAVEL_MODES.DRIVING:
      return 'attraction-marker driving';
    case TRAVEL_MODES.TRANSIT:
      return 'attraction-marker transit';
    case TRAVEL_MODES.BICYCLING:
      return 'attraction-marker bicycling';
    default:
      return 'attraction-marker';
  }
};

// 处理地图标记点击
const onMarkerTap = (e) => {
  const markerId = e.markerId;
  selectedMarker.value = markerId;

  // 更新地图中心到选中的标记
  if (attractions.value[markerId] && attractions.value[markerId].location) {
    const [longitude, latitude] = attractions.value[markerId].location.split(',').map(Number);
    mapCenter.value = { latitude, longitude };
  }
};

// 处理标记气泡点击
const onCalloutTap = (e) => {
  const markerId = e.markerId;
  selectedMarker.value = markerId;
};

// 关闭信息卡片
const closeInfoCard = () => {
  selectedMarker.value = null;
};

// 导航到选中的景点
const navigateToAttraction = () => {
  if (selectedMarker.value === null || !attractions.value[selectedMarker.value]) {
    return;
  }

  const attraction = attractions.value[selectedMarker.value];
  const [longitude, latitude] = attraction.location.split(',').map(Number);

  // 使用系统导航
  uni.openLocation({
    latitude: latitude,
    longitude: longitude,
    name: attraction.originalName || attraction.name,
    address: getSelectedAttractionAddress(),
    success: () => {
      console.log('导航成功打开');
    },
    fail: (err) => {
      console.error('导航打开失败:', err);
      uni.showToast({
        title: '无法打开导航',
        icon: 'none'
      });
    }
  });
};

// 获取选中景点的名称
const getSelectedAttractionName = () => {
  if (selectedMarker.value === null || !attractions.value[selectedMarker.value]) {
    return '';
  }
  return attractions.value[selectedMarker.value].originalName ||
    attractions.value[selectedMarker.value].name;
};

// 获取选中景点的地址
const getSelectedAttractionAddress = () => {
  if (selectedMarker.value === null ||
    !attractions.value[selectedMarker.value] ||
    !attractions.value[selectedMarker.value].geocode) {
    return '';
  }

  const geocode = attractions.value[selectedMarker.value].geocode;
  return geocode.formatted_address || '';
};

// 地图缩放
const zoomMap = (zoomIn) => {
  if (zoomIn) {
    mapScale.value = Math.min(mapScale.value + 1, 20);
  } else {
    mapScale.value = Math.max(mapScale.value - 1, 5);
  }
};

// 移动到当前位置
const moveToCurrentLocation = async () => {
  try {
    const response = await getIpLocation();
    if (response.data && response.data.status === '1') {
      // 从rectangle中提取经纬度
      const [rectangle1, rectangle2] = response.data.rectangle.split(';');
      const [lng1, lat1] = rectangle1.split(',').map(Number);
      const [lng2, lat2] = rectangle2.split(',').map(Number);

      // 计算中心点
      const centerLng = (lng1 + lng2) / 2;
      const centerLat = (lat1 + lat2) / 2;

      // 更新地图中心点
      mapCenter.value = {
        latitude: centerLat,
        longitude: centerLng
      };

      // 添加当前位置标记
      const currentLocationMarker = {
        id: 'current-location',
        latitude: centerLat,
        longitude: centerLng,
        title: '当前位置',
        iconPath: '/static/images/location.png', // 使用定位图标
        width: 32,
        height: 32,
        callout: {
          content: '当前位置',
          color: '#FFFFFF',
          fontSize: 14,
          textAlign: 'center',
          bgColor: '#007AFF',
          borderRadius: 15,
          padding: 5,
          display: 'ALWAYS'
        }
      };

      // 更新地图标记数组，确保当前位置标记在最前面
      mapMarkers.value = [currentLocationMarker, ...mapMarkers.value];

      // 更新城市信息
      if (response.data.city) {
        city.value = response.data.city;
        manualCity.value = response.data.city;
      }
    } else {
      throw new Error('获取位置失败');
    }
  } catch (err) {
    console.error('获取位置失败:', err);
    uni.showToast({
      title: '无法获取当前位置',
      icon: 'none'
    });
  }
};

// 切换步骤展开状态
const toggleStepsExpanded = () => {
  stepsExpanded.value = !stepsExpanded.value;
};

// 响应式数据
const travelList = ref([])
const refreshing = ref(false)
const hasMoreData = ref(true)
const currentUser = ref(null)
const params = ref({
  page: 0,
  size: 10
})
// 景点间距离
const attractionDistances = ref([])



// 检查景点是否包含天数信息
const checkDayInfo = (attractions) => {
  if (!attractions || attractions.length === 0) return false;
  return attractions.some(attraction => attraction.dayTitle);
};


// 路线数据相关
const routeDataId = ref(null);
const isExistingRoute = ref(false);
const travelPlanId = ref(null);

// 打开城市选择器
const openCitySelector = () => {
  uni.navigateTo({
    url: '/pages/commpoent/findcity?source=AI-travel'
  });
};
</script>

<style scoped lang="scss">
// 颜色变量
$primary-color: #3366FF;
$primary-light: rgba($primary-color, 0.1);
$accent-color: #FF6B6B;
$card-background: #FFFFFF;
$background-color: #F5F7FA;
$text-primary: #2D3748;
$text-secondary: #718096;
$text-muted: #A0AEC0;
$border-color: #E2E8F0;
$shadow-sm: 0 2px 4px rgba(0, 0, 0, 0.05);
$shadow-md: 0 4px 6px rgba(0, 0, 0, 0.1);
$shadow-lg: 0 10px 15px rgba(0, 0, 0, 0.1);
$success-color: #48BB78;
$warning-color: #ECC94B;
$error-color: #F56565;
$info-color: #4299E1;

// 交通方式颜色
$walking-color: #4CD964;
$driving-color: #007AFF;
$transit-color: #5856D6;
$bicycling-color: #FF9500;

// 圆角和间距变量
$radius-sm: 4px;
$radius-md: 8px;
$radius-lg: 12px;
$radius-xl: 20px;
$spacing-xs: 4px;
$spacing-sm: 8px;
$spacing-md: 16px;
$spacing-lg: 24px;
$spacing-xl: 32px;

.smart-travel {
  min-height: 100vh;
  background-color: $background-color;
  font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Display', sans-serif;
  color: $text-primary;

  // 页面头部
  .header {
    padding: $spacing-md $spacing-md $spacing-lg;
    background-color: $card-background;
    border-bottom-left-radius: $radius-lg;
    border-bottom-right-radius: $radius-lg;
    box-shadow: $shadow-sm;
    margin-bottom: $spacing-md;

    .nav-bar {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: $spacing-sm 0;

      .back-btn,
      .action-btn {
        width: 36px;
        height: 36px;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: $primary-light;
        border-radius: 50%;
        color: $primary-color;

        .iconfont {
          font-size: 18px;
        }
      }

      .page-title {
        font-size: 18px;
        font-weight: 600;
      }
    }

    .travel-info-card {
      margin-top: $spacing-lg;

      .travel-title {
        font-size: 24px;
        font-weight: 700;
        margin-bottom: $spacing-xs;
        display: block;
      }

      .travel-subtitle {
        font-size: 14px;
        color: $text-secondary;
      }
    }
  }

  // 手动输入表单
  .input-form {
    background-color: $card-background;
    margin: 0 $spacing-md $spacing-md;
    padding: $spacing-md;
    border-radius: $radius-lg;
    box-shadow: $shadow-sm;

    .form-row {
      display: flex;
      flex-direction: column;
      margin-bottom: $spacing-md;
      
      .form-item {
        display: flex;
        flex-direction: column;
        margin-bottom: $spacing-sm;
        
        .form-label {
          font-size: 14px;
          color: $text-secondary;
          margin-bottom: $spacing-xs;
        }
        
        .form-input-container {
          display: flex;
          align-items: center;
          gap: $spacing-sm;
          
          .form-input {
            flex: 1;
            height: 40px;
            padding: 0 $spacing-sm;
            border: 1px solid $border-color;
            border-radius: 4px;
            font-size: 14px;
            color: $text-primary;
            background-color: $background-color;
            
            &::placeholder {
              color: $text-secondary;
            }
          }
          
          .add-btn {
            min-width: 60px;
            height: 40px;
            padding: 0 $spacing-sm;
            background-color: $accent-color;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 14px;
            display: flex;
            align-items: center;
            justify-content: center;
            
            .btn-text {
              color: white;
            }
            
            &:active {
              opacity: 0.8;
            }
          }
        }
      }
    }
  }

  // 出行方式选择器
  .travel-mode-selector {
    margin: 0 $spacing-md $spacing-md;

    .travel-mode-tabs {
      display: flex;
      background-color: $card-background;
      border-radius: $radius-xl;
      box-shadow: $shadow-sm;
      overflow: hidden;

      .mode-tab {
        flex: 1;
        padding: $spacing-md 0;
        display: flex;
        flex-direction: column;
        align-items: center;
        color: $text-secondary;
        position: relative;
        transition: all 0.3s ease;

        &::after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 20%;
          right: 20%;
          height: 3px;
          background-color: transparent;
          border-radius: 3px 3px 0 0;
          transition: all 0.3s ease;
        }

        .iconfont {
          font-size: 20px;
          margin-bottom: $spacing-xs;
        }

        .mode-name {
          font-size: 14px;
          font-weight: 500;
        }

        &.active {
          color: $primary-color;

          &::after {
            background-color: $primary-color;
          }

          // 为不同出行方式设置不同激活色
          &:nth-child(1) {
            color: $walking-color;

            &::after {
              background-color: $walking-color;
            }
          }

          &:nth-child(2) {
            color: $driving-color;

            &::after {
              background-color: $driving-color;
            }
          }

          &:nth-child(3) {
            color: $transit-color;

            &::after {
              background-color: $transit-color;
            }
          }

          &:nth-child(4) {
            color: $bicycling-color;

            &::after {
              background-color: $bicycling-color;
            }
          }
        }
      }
    }
  }

  // 地图容器
  .map-container {
    margin: 0 $spacing-md $spacing-md;
    height: 300px;
    border-radius: $radius-lg;
    overflow: hidden;
    background-color: #E5E7EB;
    position: relative;
    box-shadow: $shadow-md;

    .interactive-map {
      width: 100%;
      height: 100%;
    }

    // 地图控件
    .map-controls {
      position: absolute;
      right: 10px;
      bottom: 80px;
      z-index: 10;

      .map-control {
        width: 36px;
        height: 36px;
        background-color: white;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 8px;
        font-size: 18px;
        color: $text-primary;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
      }
    }

    // 景点信息卡片
    .map-info-card {
      position: absolute;
      left: 10px;
      right: 10px;
      bottom: 10px;
      z-index: 10;
      background-color: white;
      border-radius: $radius-lg;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
      padding: 12px;

      .info-card-content {
        .info-card-title {
          font-size: 16px;
          font-weight: 600;
          margin-bottom: 4px;
          color: $text-primary;
        }

        .info-card-address {
          font-size: 13px;
          color: $text-secondary;
          margin-bottom: 10px;
        }

        .info-card-actions {
          display: flex;
          justify-content: space-between;

          .card-action {
            padding: 6px 12px;
            border-radius: 16px;
            font-size: 14px;
            text-align: center;

            &.navigate {
              background-color: $primary-color;
              color: white;
              flex: 3;
            }

            &.close {
              background-color: $border-color;
              color: $text-secondary;
              flex: 1;
              margin-left: 8px;
            }
          }
        }
      }
    }

    // 各种状态显示
    .loading-state,
    .error-state,
    .empty-state {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: rgba(255, 255, 255, 0.8);
      backdrop-filter: blur(2px);

      .loading-content,
      .error-content {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: $spacing-lg;
        background-color: rgba(255, 255, 255, 0.9);
        border-radius: $radius-lg;
        box-shadow: $shadow-md;
      }

      .iconfont {
        font-size: 32px;
        margin-bottom: $spacing-md;
      }

      .loading-text,
      .error-text,
      .empty-text {
        font-size: 15px;
        margin-bottom: $spacing-md;
        text-align: center;
      }

      .retry-btn {
        padding: $spacing-sm $spacing-lg;
        background-color: $primary-color;
        color: white;
        border-radius: $radius-md;
        font-weight: 500;
      }
    }

    .loading-state .iconfont {
      color: $info-color;
      animation: spin 1.5s linear infinite;
    }

    .error-state .iconfont {
      color: $error-color;
    }

    .empty-state .iconfont {
      color: $text-muted;
      font-size: 40px;
    }
  }

  // 路线详情
  .route-details {
    margin: 0 $spacing-md $spacing-md;
    background-color: $card-background;
    border-radius: $radius-lg;
    box-shadow: $shadow-sm;
    overflow: hidden;

    .route-summary {
      display: flex;
      padding: $spacing-md;
      background-color: rgba($primary-color, 0.05);
      border-bottom: 1px solid $border-color;

      .summary-item {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;

        .summary-value {
          font-size: 18px;
          font-weight: 600;
          color: $primary-color;
          margin-bottom: $spacing-xs;
        }

        .summary-label {
          font-size: 13px;
          color: $text-secondary;
        }
      }
    }

    .route-segments {
      padding: $spacing-md;

      .segment-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: $spacing-md;

        .segment-title {
          font-size: 17px;
          font-weight: 600;
        }
      }

      .segments-container {
        .segment-item {
          display: flex;
          padding: $spacing-md 0;
          border-bottom: 1px solid $border-color;

          &:last-child {
            border-bottom: none;
          }

          .segment-marker {
            width: 28px;
            height: 28px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: $primary-light;
            color: $primary-color;
            margin-right: $spacing-md;
            flex-shrink: 0;

            .segment-index {
              font-size: 14px;
              font-weight: 500;
            }
          }

          .segment-content {
            flex: 1;

            .segment-header {
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: $spacing-xs;

              .segment-name {
                font-size: 15px;
                font-weight: 500;
              }

              .segment-distance {
                font-size: 13px;
                color: $text-secondary;
                background-color: $primary-light;
                padding: 2px 8px;
                border-radius: 12px;
              }
            }

            .segment-detail {
              font-size: 13px;
              color: $text-secondary;
            }
          }
        }
      }
    }
  }

  // 景点列表面板
  .attractions-panel {
    margin: 0 $spacing-md $spacing-xl;
    background-color: $card-background;
    border-radius: $radius-lg $radius-lg 0 0;
    box-shadow: $shadow-sm;
    overflow: hidden;

    .panel-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: $spacing-md;
      border-bottom: 1px solid $border-color;

      .panel-title {
        font-size: 17px;
        font-weight: 600;
      }

      .panel-count {
        font-size: 14px;
        font-weight: 500;
        background-color: $primary-light;
        color: $primary-color;
        width: 24px;
        height: 24px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }

    .attractions-list {
      max-height: 300px;
      overflow-y: auto;
      padding: $spacing-sm;

      .attraction-item {
        display: flex;
        align-items: center;
        padding: $spacing-md;
        margin: $spacing-xs 0;
        background-color: $card-background;
        border: 1px solid rgba($border-color, 0.5);
        border-radius: $radius-md;
        position: relative;
        transition: all 0.3s ease;

        &:hover {
          box-shadow: $shadow-sm;
        }

        &.dragging {
          opacity: 0.8;
          box-shadow: $shadow-md;
          background-color: $primary-light;
          z-index: 10;
        }

        &.drag-target {
          box-shadow: none;
          border: 2px dashed $primary-color;
          transform: scale(1.02);
        }

        .drag-handle {
          width: 28px;
          height: 28px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: $text-muted;
          margin-right: $spacing-sm;

          .iconfont {
            font-size: 14px;
          }
        }

        .attraction-marker {
          width: 32px;
          height: 32px;
          border-radius: 50%;
          background-color: $primary-color;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: $spacing-md;
          flex-shrink: 0;
          transition: all 0.3s ease;

          .marker-text {
            font-size: 14px;
            font-weight: 500;
            color: white;
          }

          &.walking {
            background-color: $walking-color;
          }

          &.driving {
            background-color: $driving-color;
          }

          &.transit {
            background-color: $transit-color;
          }

          &.bicycling {
            background-color: $bicycling-color;
          }

          &.selected {
            background-color: $accent-color;
            transform: scale(1.1);
            box-shadow: 0 0 0 4px rgba($accent-color, 0.3);
          }
        }

        .attraction-info {
          flex: 1;
          margin-right: $spacing-md;

          .attraction-name {
            font-size: 15px;
            font-weight: 500;
            margin-bottom: 4px;
            display: block;
          }

          .attraction-schedule {
            font-size: 13px;
            color: $text-secondary;
          }
        }

        .attraction-action {
          width: 28px;
          height: 28px;
          background-color: rgba($error-color, 0.1);
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          color: $error-color;

          .iconfont {
            font-size: 14px;
          }
        }
      }

      .empty-list {
        padding: $spacing-xl;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;

        .empty-icon {
          font-size: 40px;
          margin-bottom: $spacing-md;
        }

        .empty-text {
          font-size: 15px;
          color: $text-muted;
          text-align: center;
        }
      }
    }

    .panel-footer {
      padding: $spacing-md;
      border-top: 1px solid $border-color;
      display: flex;
      justify-content: space-between;

      .action-button {
        flex: 1;
        height: 44px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: $radius-md;
        font-size: 15px;
        font-weight: 500;

        .iconfont {
          margin-right: $spacing-xs;
        }

        &.primary {
          background-color: $primary-color;
          color: white;
          margin-right: $spacing-sm;
        }

        &.secondary {
          background-color: $primary-light;
          color: $primary-color;
        }
      }
    }
  }
}

// 定义关键帧动画
@keyframes spin {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 添加响应式适配
@media screen and (max-width: 375px) {
  .smart-travel {
    .route-details {
      .route-summary {
        .summary-item {
          .summary-value {
            font-size: 16px;
          }
        }
      }
    }

    .travel-mode-selector {
      .travel-mode-tabs {
        .mode-tab {
          .mode-name {
            font-size: 12px;
          }
        }
      }
    }
  }
}

.day-attractions-container {
  background-color: #fff;
  border-radius: 16rpx;
  margin: 20rpx;
  padding: 30rpx 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 30rpx;
  text-align: center;
  color: #333;
  position: relative;
}

.section-title:after {
  content: '';
  position: absolute;
  bottom: -10rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 80rpx;
  height: 4rpx;
  background-color: #4CAF50;
  border-radius: 2rpx;
}

.day-group {
  margin-bottom: 40rpx;
}

.day-group:last-child {
  margin-bottom: 20rpx;
}

.day-title {
  font-size: 30rpx;
  font-weight: bold;
  padding: 16rpx 20rpx;
  background-color: #f0f8ff;
  border-left: 8rpx solid #4CAF50;
  margin-bottom: 20rpx;
  border-radius: 8rpx;
  color: #333;
}

.day-attractions-list {
  padding: 0 10rpx;
}

.day-attractions-list .attraction-item {
  padding: 20rpx;
  border-bottom: 1px solid #f5f5f5;
  display: flex;
  flex-direction: column;
  transition: all 0.3s;
}

.day-attractions-list .attraction-item:active {
  background-color: #f9f9f9;
}

.day-attractions-list .attraction-item:last-child {
  border-bottom: none;
}

.day-attractions-list .attraction-name {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 8rpx;
  font-weight: 500;
}

.day-attractions-list .attraction-desc {
  font-size: 24rpx;
  color: #666;
  line-height: 1.5;
}
</style>